package com.dh.bm.common;

import java.sql.*;
import java.util.ResourceBundle;

public class JDBCUtil {
    private static String url;
    private static String user;
    private static String password;
    private static Connection connection;
    private static PreparedStatement statement;

    // 静态代码块
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");// 反射
            ResourceBundle rb = ResourceBundle.getBundle("jdbc");
            url = rb.getString("url");
            user = rb.getString("user");
            password = rb.getString("password");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 获取连接
    private static Connection getConnection() {
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    // 获取statement对象
    public static PreparedStatement getStatement(String sql) {
        if (connection == null) {
            getConnection();
        }
        if (connection != null) {
            try {
                statement = connection.prepareStatement(sql);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return statement;
    }

    // 关闭
    public static void close(ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        close();

    }

    public static void close() {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}
